package com.platform.common.config.redis;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.util.ArrayList;
import java.util.List;

/**
 * @author prngshuiming
 * @date: 2018/6/12 16:16
 */
@Configuration
public class RedisCacheConfiguration  {
    Logger logger = LoggerFactory.getLogger(RedisCacheConfiguration.class);
    private static final String DEFAULT_REDIS_SEPARATOR = ";";

    private static final String HOST_PORT_SEPARATOR = ":";
    @Value("${spring.redis.host}")
    private String host;

    @Value("${spring.redis.port}")
    private int port;

    @Value("${spring.redis.timeout}")
    private int timeout;

    @Value("${spring.redis.jedis.pool.max-idle}")
    private int maxIdle;
    @Value("${spring.redis.jedis.pool.min-idle}")
    private int minIdle;

    @Value("${spring.redis.jedis.pool.max-wait}")
    private long maxWaitMillis;
    @Value("${spring.redis.password}")
    private String password;
    @Value("${spring.redis.jedis.pool.max-active}")
    private int maxTotal;
    @Value("${jedis.redis.pool.testOnBorrow}")
    private boolean testOnBorrow;
    @Value("${jedis.redis.blockWhenExhausted}")
    private boolean blockWhenExhausted;
    @Bean
    public JedisPool[] redisPoolFactory() {

        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxIdle(maxIdle);
        jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
        jedisPoolConfig.setMaxTotal(maxTotal);
        jedisPoolConfig.setMinIdle(minIdle);
        jedisPoolConfig.setTestOnBorrow(testOnBorrow);
        jedisPoolConfig.setBlockWhenExhausted(blockWhenExhausted);
//        JedisPool jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout, password);
//        return jedisPool;
        // 生成连接池
        List<JedisPool> jedisPoolList = new ArrayList<JedisPool>();
        for (String redisUrl : host.split(DEFAULT_REDIS_SEPARATOR)) {
            String[] redisUrlInfo = host.split(HOST_PORT_SEPARATOR);
            JedisPool pool = new JedisPool(jedisPoolConfig, redisUrlInfo[0], port, timeout, password);
            jedisPoolList.add(pool);
        }
        JedisPool[] jedisPools = new JedisPool[0];
        jedisPools = jedisPoolList.toArray(jedisPools);
        logger.info("JedisPool注入成功！！");
        logger.info("redis地址：" + host + ":" + port);
        return jedisPools;
    }

}
